# -*- coding: utf-8 -*-
# Created by 'Zhou Bingbing'  on 2019/7/26

import numpy as np
import matplotlib.pyplot as plt

class linear:
    def __init__(self):
        self.a=0
        self.b=0
    def fit(self,x,y):
        molecule=0
        dnominator=0
        x_mean=np.mean(x)
        y_mean=np.mean(y)
        for i in range(len(x)):
            molecule+=(x[i]-x_mean)*(y[i]-y_mean)
            dnominator+=(x[i]-x_mean)**2
        self.a= float(molecule/dnominator)
        self.b=y_mean-self.a*x_mean
    def predict(self,x):
        return self.a*x+self.b
x = np.array([1, 3, 2, 1, 3])
y = np.array([14, 24, 18, 17, 27])
# 画点
plt.scatter(x, y, c='r', marker='o')
lin = linear()
lin.fit(x, y)
# 划线
x = np.arange(0, 5, 1)
y = lin.predict(x)
print(y)
plt.plot(x, y, 'b')
plt.show()
